/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package look.elements.admin;

/**
 * Диалоговое окно добавление нового администратора
 *
 * @author Julien Sorel
 */

import CommonTools.Actions;
import CommonTools.Constants;
import CommonTools.DesignTools;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;

public class AddAdminWindow extends JDialog {

    /*****************************************************
     * Переменные класса
     ****************************************************/

    //Список администраторов, который после будем обновлять
    public JList aList;

    //Поля и чекбокс
    public JTextField aName, aFam, aOtch, aMail, aLogin, aPhone;
    public JPasswordField aPassword;
    JLabel aNameL, aFamL, aOtchL, aMailL, aLoginL, aPasswordL, aPhoneL;
    JCheckBox showPassword, rootCb;
    public JButton createB, cancelB;
    char enabled = '•', disabled = '\0';

    //Конструктор
    public AddAdminWindow(JList list, JFrame frame)
    {
        super(frame, "Добавление администратора", true);

        this.aList = list;

        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        this.setResizable(false);

        /***********************************************************
         * Создаем компоновщик и настраиваем его примитивно
         **********************************************************/
        Container c = this.getContentPane();
        c.setLayout(new GridBagLayout());

        GridBagConstraints gbcLabels = new GridBagConstraints();

        gbcLabels.weightx = 0.5;
        gbcLabels.weighty = 0.5;
        gbcLabels.gridx = 0;
        gbcLabels.ipadx = 50;
        gbcLabels.fill = GridBagConstraints.NONE;
        gbcLabels.anchor = GridBagConstraints.NORTHWEST;
        gbcLabels.insets = new Insets(8, 10, 5, 0);

        GridBagConstraints gbcFields = new GridBagConstraints();
        gbcFields.weightx = 0.5;
        gbcFields.weighty = 0.5;
        gbcFields.gridx = 1;
        gbcFields.ipadx = 200;
        gbcFields.fill = GridBagConstraints.HORIZONTAL;
        gbcFields.anchor = GridBagConstraints.NORTHWEST;
        gbcFields.insets = new Insets(3,0,0, 10);

        KeyHandler keyHandler = new KeyHandler(this);

        /***********************************************************
         * Создаем поля и добавляем их
         **********************************************************/
        aName = new JTextField();
        aName.setForeground(Constants.NORMAL_COLOR);
        aNameL = new JLabel("Имя:");
        aName.addKeyListener(keyHandler);
        gbcLabels.gridy = 0;
        gbcFields.gridy = 0;
        c.add(aNameL, gbcLabels);
        c.add(aName, gbcFields);

        aFam = new JTextField();
        aFam.setForeground(Constants.NORMAL_COLOR);
        aFam.addKeyListener(keyHandler);
        aFamL = new JLabel("Фамилия:");
        gbcLabels.gridy = 1;
        gbcFields.gridy = 1;
        c.add(aFamL, gbcLabels);
        c.add(aFam, gbcFields);

        aOtch = new JTextField();
        aOtch.setForeground(Constants.NORMAL_COLOR);
        aOtch.addKeyListener(keyHandler);
        aOtchL = new JLabel("Отчество:");
        gbcLabels.gridy = 2;
        gbcFields.gridy = 2;
        c.add(aOtchL, gbcLabels);
        c.add(aOtch, gbcFields);

        aLogin = new JTextField();
        aLogin.setForeground(Constants.NORMAL_COLOR);
        aLogin.addKeyListener(keyHandler);
        aLoginL = new JLabel("Логин:");
        gbcLabels.gridy = 3;
        gbcFields.gridy = 3;
        c.add(aLoginL, gbcLabels);
        c.add(aLogin, gbcFields);

        aPassword = new JPasswordField();
        aPassword.setForeground(Constants.NORMAL_COLOR);
        aPassword.addKeyListener(keyHandler);
        aPasswordL = new JLabel("Пароль:");
        aPassword.setEchoChar('∙');
        gbcLabels.gridy = 4;
        gbcFields.gridy = 4;
        c.add(aPasswordL, gbcLabels);
        c.add(aPassword, gbcFields);

        aMail = new JTextField();
        aMail.setForeground(Constants.NORMAL_COLOR);
        aMailL = new JLabel("E-mail:");
        gbcLabels.gridy = 6;
        gbcFields.gridy = 6;
        c.add(aMailL, gbcLabels);
        c.add(aMail, gbcFields);

        aPhone = new JTextField();
        aPhone.setForeground(Constants.NORMAL_COLOR);
        aPhoneL = new JLabel("Телефон:");
        gbcLabels.gridy = 7;
        gbcFields.gridy = 7;
        c.add(aPhoneL, gbcLabels);
        c.add(aPhone, gbcFields);

        showPassword = new JCheckBox("Показать пароль");
        showPassword.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    if (showPassword.isSelected())
                        aPassword.setEchoChar(disabled);
                    else
                        aPassword.setEchoChar(enabled);
                }
            });
        gbcFields.gridy = 5;
        c.add(showPassword, gbcFields);

        rootCb = new JCheckBox("Суперадминистратор");
        gbcFields.gridy = 8;
        c.add(rootCb, gbcFields);

        createB = new JButton("Создать");
        createB.setEnabled(false);
        cancelB = new JButton("Отмена");
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(createB);
        buttonPanel.add(cancelB);
        gbcFields.gridwidth = 2;
        gbcFields.gridx = 0;
        gbcFields.gridy = 9;
        c.add(buttonPanel, gbcFields);

        //createB.addActionListener(new AddAdminEvent(this, list));
        cancelB.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    hideMe();
                }
            });

        createB.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    addAdmin();
                }
            });

        Toolkit tool = this.getToolkit();
        Dimension d = tool.getScreenSize();
        
        /***********************************************
         * Вешаем слушателей событий (счетчики короче)
         **********************************************/
        //public JTextField aName, aFam, aOtch, aMail, aLogin, aPhone;
        //public JPasswordField aPassword;
        aName.addKeyListener(new KeyAdapter()
            {
                @Override
                public void keyPressed(KeyEvent e)
                {
                    if (aName.getText().length() > 19)
                        aName.setForeground(Constants.ERROR_COLOR);
                    else
                        aName.setForeground(Constants.NORMAL_COLOR);
                }
            });
        aFam.addKeyListener(new KeyAdapter()
            {
                @Override
                public void keyPressed(KeyEvent e)
                {
                    if (aFam.getText().length() > 19)
                        aFam.setForeground(Constants.ERROR_COLOR);
                    else
                        aFam.setForeground(Constants.NORMAL_COLOR);
                }
            });
        aOtch.addKeyListener(new KeyAdapter()
            {
                @Override
                public void keyPressed(KeyEvent e)
                {
                    if (aOtch.getText().length() > 19)
                        aOtch.setForeground(Constants.ERROR_COLOR);
                    else
                        aOtch.setForeground(Constants.NORMAL_COLOR);
                }
            });
        aMail.addKeyListener(new KeyAdapter()
            {
                @Override
                public void keyPressed(KeyEvent e)
                {
                    if (aMail.getText().length() > 49)
                        aMail.setForeground(Constants.ERROR_COLOR);
                    else
                        aMail.setForeground(Constants.NORMAL_COLOR);
                }
            });
        aLogin.addKeyListener(new KeyAdapter()
            {
                @Override
                public void keyPressed(KeyEvent e)
                {
                    if (aLogin.getText().length() > 19)
                        aLogin.setForeground(Constants.ERROR_COLOR);
                    else
                        aLogin.setForeground(Constants.NORMAL_COLOR);
                }
            });
        aPhone.addKeyListener(new KeyAdapter()
            {
                @Override
                public void keyPressed(KeyEvent e)
                {
                    if (aPhone.getText().length() > 19)
                        aPhone.setForeground(Constants.ERROR_COLOR);
                    else
                        aPhone.setForeground(Constants.NORMAL_COLOR);
                }
            });
        aPassword.addKeyListener(new KeyAdapter()
            {
                @Override
                public void keyPressed(KeyEvent e)
                {
                    if (aPassword.getText().length() > 19)
                        aPassword.setForeground(Constants.ERROR_COLOR);
                    else
                        aPassword.setForeground(Constants.NORMAL_COLOR);
                }
            });


        this.pack();
        this.validate();
        this.setLocation((int)((d.getWidth() - this.getWidth())/2), (int) ((d.getHeight() - this.getHeight())/2));
        this.setVisible(true);
    }

    private class KeyHandler implements KeyListener
    {
        AddAdminWindow aaw;

        public KeyHandler(AddAdminWindow aaw)
        {
            this.aaw = aaw;
        }

        public void keyTyped(KeyEvent e) {
                aaw.createB.setEnabled((aaw.aName.getText().length() > 0) && (aaw.aFam.getText().length() > 0) &&
                               (aaw.aOtch.getText().length() > 0) && (aaw.aLogin.getText().length() > 0) &&
                               (aaw.aPassword.getText().length() > 0));
        }

        public void keyPressed(KeyEvent e) {}

        public void keyReleased(KeyEvent e) {}

    }

    /**
     * Процедура добавления нового администратора
     * Вызывается по нажатию на кнопку
     */
    private void addAdmin()
    {
        int root;
        if (rootCb.isSelected())
            root = 1;
        else
            root = 0;

        if (aName.getForeground().equals(Constants.NORMAL_COLOR) && 
            aFam.getForeground().equals(Constants.NORMAL_COLOR) &&
            aLogin.getForeground().equals(Constants.NORMAL_COLOR) &&
            aPassword.getForeground().equals(Constants.NORMAL_COLOR) &&
            aOtch.getForeground().equals(Constants.NORMAL_COLOR) &&
            aMail.getForeground().equals(Constants.NORMAL_COLOR) &&
            aPhone.getForeground().equals(Constants.NORMAL_COLOR))

            if (!Actions.isAdminThere(aLogin.getText()))
            {
                Actions.addAdmin(aName.getText(), aFam.getText(), aOtch.getText(), aLogin.getText(), aPassword.getText(), root, aMail.getText(), aPhone.getText());
                Actions.refreshAdminList(aList);
            }
            else
                DesignTools.showMessage("Ошибка", "Администратор с таким логином уже существует", true);
        else
            DesignTools.showMessage("Ошибка", "Администратор не создан\n"
                    + "Если в каком-то из полей текст красного цвета,\n"
                    + "то сократите текст, пока он не станет черным.", true);
    }

    /**
     * Функция скрытия окна
     */
    private void hideMe()
    {
        this.dispose();
    }

}
